<?php
// +----------------------------------------------------------------------
// | MC PHP[基于ThinkPHP6.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://www.mingchangruanjian.com
// +----------------------------------------------------------------------
// | Author jokerfei [ jokerfei377@gmail.com ]
// +----------------------------------------------------------------------
// | 铭畅软件 技术部 出品
// +----------------------------------------------------------------------
// 验证码获取和验证接口

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\common\model\LogSms;
use app\common\service\ApiReturn;

class VerifyCode extends Base
{
    /**
     * 获取短信验证码
     * @Author jokerfei [ jokerfei377@gmail.com ]
     * @param array $data 参数
     */
    public function getSmsCode(array $data = [], array $user = [])
    {
        if (!$data['mobile']) {
            return ApiReturn::r(0, [], '手机号错误');
        }
        //注册场景下判断手机号存不存在
        if ($data['type'] == 1) {
            $mobile_count = \app\admin\model\user\User::where('mobile', $data['mobile'])->count();
            if ($mobile_count) {
                return ApiReturn::r(0, [], '手机号已存在，无法注册');
            }
        }

        //登录,忘记密码场景下判断手机号存不存在
        if ($data['type'] == 3 || $data['type'] == 2 || $data['type'] == 5) {
            $mobile_count = \app\admin\model\user\User::where('mobile', $data['mobile'])->count();
            if (!$mobile_count) {
                return ApiReturn::r(0, [], '此账号不存在，请先注册！');
            }
        }
        //修改手机号，去除会员对应的手机号
        if ($data['type'] == 4) {
            if(!$user){
                return ApiReturn::r(0, [], '登录后修改手机号');
            }
            $mobile = \app\admin\model\user\User::where('id', $user['id'])->value('mobile');
            if (!$mobile || $mobile != $data['mobile']) {
                return ApiReturn::r(0, [], '手机号错误');
            }
        }
        if (!preg_match("/^1\d{10}$/", $data['mobile'])) {
            return ApiReturn::r(0, [], '手机号码格式错误');
        }

        $isTest = $data['is_test'] == 1;
        $phoneVerify = rand(100000, 999999);

        try {
            // 阿里短信
            LogSms::sendDysms($phoneVerify, $data['mobile'], $data['type'], $isTest);
        } catch (\Exception $e) {
            return ApiReturn::r(0, [], $e->getMessage());
        }

        if ($isTest) {
            return ApiReturn::r(1, ['code' => $phoneVerify], '发送成功');
        }

        return ApiReturn::r(1, [], '发送成功');
    }

}
